package com.invoicerecognition.backend.service.impl.teacher;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.invoicerecognition.backend.mapper.InvoiceMapper;
import com.invoicerecognition.backend.mapper.StudentMapper;
import com.invoicerecognition.backend.mapper.TeacherMapper;
import com.invoicerecognition.backend.model.dto.Invoice;
import com.invoicerecognition.backend.model.dto.Student;
import com.invoicerecognition.backend.model.dto.Teacher;
import com.invoicerecognition.backend.model.dto.User;
import com.invoicerecognition.backend.service.impl.utils.UserDetailsImpl;
import com.invoicerecognition.backend.service.teacher.GetStudentInvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class GetStudentInvoiceServiceImpl implements GetStudentInvoiceService {

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public JSONObject getStudentInvoice(int page) {

        JSONObject resp = new JSONObject();

        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();
        Integer userId = user.getId();

        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Teacher teacher = teacherMapper.selectOne(queryWrapper);

        if (teacher == null) {
            resp.put("error_message", "error");
            return resp;
        }
        else {
            Set<String> studentUserIds = teacher.getStudents();
            if (studentUserIds.isEmpty()) {
                resp.put("error_message", "error");
                return resp;
            }
            else {
                // 实现分页，IPage是mybatisplus的配置
                IPage<Invoice> recordIPage = new Page<>(page, 10);   // 第一个参数是第几页，第二个参数是每一页里面有多少个项目
                QueryWrapper<Invoice> queryWrapperStudent = new QueryWrapper<>();
                queryWrapperStudent.orderByDesc("id");
                int index = 0;
                int size = studentUserIds.size();
                for (String studentUserId : studentUserIds) {
                    index++;
                    if (index == size) {
                        // 最后一个元素
                        queryWrapperStudent.eq("user_id", Integer.parseInt(studentUserId));
                    } else {
                        // 其他元素
                        queryWrapperStudent.eq("user_id", Integer.parseInt(studentUserId)).or();
                    }
                }
                List<Invoice> records = invoiceMapper.selectPage(recordIPage, queryWrapperStudent).getRecords();
                List<Student> studentInfo = new ArrayList<>();

                for (Invoice record: records) {
                    int studentUserId = record.getUserId();
                    QueryWrapper<Student> queryWrapperInfo = new QueryWrapper<>();
                    queryWrapperInfo.eq("user_id", studentUserId);
                    Student student = studentMapper.selectOne(queryWrapperInfo);
                    studentInfo.add(student);
                }

                resp.put("records", records);
                resp.put("records_count", invoiceMapper.selectCount(queryWrapperStudent));
                resp.put("student_info", studentInfo);
                resp.put("error_message", "success");
                return resp;
            }
        }
    }
}
